﻿/*  Francis Nino Seisei 
 *  ©2012 Francis Antonio Bolaños Arias.
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Seisei.Global;
using Seisei.IO;
using Seisei.Berta.Generator;
using Seisei.Nino.Reader;
using Seisei.Nino.Generator;
using ScintillaNet;
using WeifenLuo.WinFormsUI.Docking;
using System.Threading;
using System.Globalization;

namespace Seisei
{
    public partial class GUI : Form
    {
        private DockContent DCNino;
        private UCNino ucNino;
        private DockContent DCCode;
        private UCCode ucCode;
        private DockContent DCBerta;
        private UCBerta ucBerta;
        private DockContent DCTypes;
        private UCTypes ucTypes;
        private DockContent DCOutput;
        private UCSalida Salida;
        private DockContent DCHelp;
        private UCAyuda ucHelp;
        private DockContent DCExplorer;
        private UCExplorador Explorador;

        public GUI()
        {
            InitializeComponent();
            MostrarDCNino();
            MostrarDCCode();
            MostrarDCBerta();
            MostrarDCTypes();
            MostrarDCHelp();
            MostrarDCOutput();
            MostrarDCExplorer();
            Salida.txtSalida.Text += "[Nino Seisei v1.0.0]\r\n";
            FileGuru.CreateNinoFilesFolders();
            CargarExplorador();
            string Local = "";
            try
            {
                Local = FileGuru.OpenUTF8File(Environment.CurrentDirectory + "\\local.conf").Replace("\r", "").Replace("\n", "");
            }
            catch (FileNotFoundException) {
                FileGuru.SaveUTF8File(Environment.CurrentDirectory + "\\local.conf", "es-CR");
                Local = "es-CR";
            }
            cargarLocalizacion(Local);
            Salida.txtSalida.Text += Global.Local.LOC001_OUTPUT_LOADING_FILES + "...\r\n";
        }

        #region "Eventos"

        private void GUI_Load(object sender, EventArgs e)
        {
            lblFecha.Text = DateTime.Now.ToString();
            this.Text = "Nino Seisei - [" + Global.Local.LOC003_WORKSPACE + " @ " + Memory.WORKSPACE + "]";
            Salida.txtSalida.Text += Global.Local.LOC002_OUTPUT_READY + ".\r\n";
            //this.
            DCNino.Activate();
            DCCode.Activate();
            DCBerta.Activate();
            DCTypes.Activate();
            DCHelp.Activate();
            DCNino.Activate();
        }

        private void cargarLocalizacion(string Local) {
            try
            {
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(Local);
            }
            catch (CultureNotFoundException) {
                Local = "en-US";
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(Local);
            }

            FileGuru.SaveUTF8File(Environment.CurrentDirectory + "\\local.conf", Local);

            if (Local.Equals("en-US"))
            {
                ucHelp.wbAyuda.DocumentText = Global.HelpEnUS.Contents;
            }
            else {
                ucHelp.wbAyuda.DocumentText = Global.Help.Contents;
            }

            //Menú Archivo
            this.tsmiArchivo.Text = global::Seisei.Properties.Strings.MenuArchivo;
            this.tsmiNuevoCodigo.Text = global::Seisei.Properties.Strings.MenuArchNuevoCodigo;
            this.tsmiNuevaPlantilla.Text = global::Seisei.Properties.Strings.MenuArchNuevaPlantilla;
            this.tsmiNuevoTipoDatos.Text = global::Seisei.Properties.Strings.MenuArchNuevoTipo;
            this.tsmiAbrir.Text = global::Seisei.Properties.Strings.MenuArchAbrir;
            this.tsmiGuardar.Text = global::Seisei.Properties.Strings.MenuArchGuardar;
            this.tsmiSalir.Text = global::Seisei.Properties.Strings.MenuArchSalir;

            //Menú Generar
            this.tsmiGenerar.Text = global::Seisei.Properties.Strings.MenuGenerar;
            this.tsmiEjecutarCodigo.Text = global::Seisei.Properties.Strings.MenuGenEjecutarCodigo;
            this.tsmiGenerarCodigo.Text = global::Seisei.Properties.Strings.MenuGenGenCodigo;
            this.tsmiNinoDatos.Text = global::Seisei.Properties.Strings.MenuGenObtCodigo;

            //Menú Lenguajes
            this.tsmiLenguajes.Text = global::Seisei.Properties.Strings.MenuLenguajes;

            //Menú Ayuda
            this.tsmiAyuda.Text = global::Seisei.Properties.Strings.MenuAyuda;
            this.tsmiContenidos.Text = global::Seisei.Properties.Strings.MenuAyudaContenidos;
            this.tsmiInicio.Text = global::Seisei.Properties.Strings.MenuAyudaVentana;
            this.tsmiAcerca.Text = global::Seisei.Properties.Strings.MenuAyudaAcerca;

            //Barra de Herramientas
            this.tsbNino.ToolTipText = global::Seisei.Properties.Strings.MenuArchNuevoCodigo;
            this.tsbBerta.ToolTipText = global::Seisei.Properties.Strings.MenuArchNuevaPlantilla;
            this.tsbTypes.ToolTipText = global::Seisei.Properties.Strings.MenuArchNuevoTipo;
            this.tsbOpen.ToolTipText = global::Seisei.Properties.Strings.MenuArchAbrir;
            this.tsbSave.ToolTipText = global::Seisei.Properties.Strings.MenuArchGuardar;
            this.tsbDatabase.ToolTipText = global::Seisei.Properties.Strings.MenuGenObtCodigo;
            this.tsbRunNino.ToolTipText = global::Seisei.Properties.Strings.MenuGenEjecutarCodigo;
            this.tsbGenCode.ToolTipText = global::Seisei.Properties.Strings.MenuGenGenCodigo;
            this.tsbContenidos.ToolTipText = global::Seisei.Properties.Strings.MenuAyudaContenidos;
            this.tsbInicio.ToolTipText = global::Seisei.Properties.Strings.MenuAyudaVentana;
            this.tsbAcerca.ToolTipText = global::Seisei.Properties.Strings.MenuAyudaAcerca;

            //Dock Contents
            DCNino.Text = global::Seisei.Properties.Strings.DCCodigo;
            DCCode.Text = global::Seisei.Properties.Strings.DCGenerado;
            DCBerta.Text = global::Seisei.Properties.Strings.DCBerta;
            DCTypes.Text = global::Seisei.Properties.Strings.DCTipos;
            DCHelp.Text = global::Seisei.Properties.Strings.DCContenidos;
            DCOutput.Text = global::Seisei.Properties.Strings.DCSalida;
            DCExplorer.Text = global::Seisei.Properties.Strings.DCExplorador;

            //Textos
            Global.Local.LOC001_OUTPUT_LOADING_FILES = global::Seisei.Properties.Strings.LOCOutputLoadingFiles;
            Global.Local.LOC002_OUTPUT_READY = global::Seisei.Properties.Strings.LOCOutputReady;
            Global.Local.LOC003_WORKSPACE = global::Seisei.Properties.Strings.LOCWorkspace;
            Global.Local.LOC004_OPENING_FILE = global::Seisei.Properties.Strings.LOCAbriendoArch;
            Global.Local.LOC005_ERROR = global::Seisei.Properties.Strings.LOCError;
            Global.Local.LOC080_WEL_NEW_NINO = global::Seisei.Properties.Strings.LOCIniNuevoNino;
            Global.Local.LOC081_WEL_NEW_BERTA = global::Seisei.Properties.Strings.LOCIniNuevoBerta;
            Global.Local.LOC082_WEL_NEW_DT = global::Seisei.Properties.Strings.LOCIniNuevoDT;
            Global.Local.LOC083_WEL_NINO_DB = global::Seisei.Properties.Strings.LOCIniNinoDB;
            Global.Local.LOC084_WEL_LICENSE = global::Seisei.Properties.Strings.LOCIniLicencia;
            Global.Local.LOC085_CLOSE = global::Seisei.Properties.Strings.LOCClose;
            Global.Local.LOC086_AB_LICENSE_3RD = global::Seisei.Properties.Strings.LOCAceLicenciaTer;

            this.Text = "Nino Seisei - [" + Global.Local.LOC003_WORKSPACE + " @ " + Memory.WORKSPACE + "]";
        }

        private void tsmiNinoDatos_Click(object sender, EventArgs e)
        {
            tsbDatabase.PerformClick();
        }

        private void ninoassis_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (Memory.GENERATING_NINO)
            {
                Memory.CODGENTAB = ucCode.scintillaCode.Text;
                Memory.BERTATAB = ucBerta.scintillaBerta.Text;
                Memory.TYPESTAB = ucTypes.scintillaDataTypes.Text;
                CargarCodigoNino();
                DCNino.Dispose();
                DCCode.Dispose();
                DCBerta.Dispose();
                DCTypes.Dispose();
                MostrarDCCode();
                MostrarDCTypes();
                MostrarDCBerta();
                MostrarDCNino();
                DCNino.Activate();
                ucCode.scintillaCode.Text = Memory.CODGENTAB;
                ucNino.scintillaNino.Text = Memory.NINOTAB;
                ucBerta.scintillaBerta.Text = Memory.BERTATAB;
                ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
                ucNino.scintillaNino.Focus();
                //tsmiEjecutarCodigo.PerformClick();
                Memory.GENERATING_NINO = false;
            }
        }

        private void inicio_FormClosed(object sender, FormClosedEventArgs e)
        {
            RespaldarCodigos();
            if (Memory.START_SELECTION == (int)Memory.STARTOPT.NewNino)
            {
                tsmiNuevoCodigo.PerformClick();
            }
            else if (Memory.START_SELECTION == (int)Memory.STARTOPT.NewBerta)
            {
                tsmiNuevaPlantilla.PerformClick();
            }
            else if (Memory.START_SELECTION == (int)Memory.STARTOPT.NewDataType)
            {
                tsmiNuevoTipoDatos.PerformClick();
            }
            //else if (Memory.START_SELECTION == (int)Memory.STARTOPT.Open)
            //{
            //    tsmiAbrir.PerformClick();
            //}
            else if (Memory.START_SELECTION == (int)Memory.STARTOPT.Database)
            {
                tsmiNinoDatos.PerformClick();
            }
            
            Memory.NINOTAB = "";
            Memory.CODGENTAB = "";
            Memory.BERTATAB = "";
            Memory.TYPESTAB = "";
            System.GC.Collect();
        }

        private void tsmiRunNino_Click(object sender, EventArgs e)
        {
            tsbRunNino.PerformClick();
        }

        private void GUI_Shown(object sender, EventArgs e)
        {
            Welcome inicio = new Welcome();
            inicio.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.inicio_FormClosed);
            inicio.ShowDialog();
        }

        private void tsmiInicio_Click(object sender, EventArgs e)
        {
            tsbInicio.PerformClick();
        }

        private void tsmiGuardar_Click(object sender, EventArgs e)
        {
            tsbSave.PerformClick();
        }

        private void tvExplorador_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                if (e.Node.ImageIndex > 0)
                {
                    Memory.NINOTAB = ucNino.scintillaNino.Text;
                    Memory.CODGENTAB = ucCode.scintillaCode.Text;
                    Memory.BERTATAB = ucBerta.scintillaBerta.Text;
                    Memory.TYPESTAB = ucTypes.scintillaDataTypes.Text;

                    string File = e.Node.FullPath;
                    File = File.Replace("Nino Seisei", Memory.WORKSPACE);

                    if (e.Node.ImageIndex == 2)
                    {
                        File += ".nino";
                        ReinicializarNino();
                        ucNino.scintillaNino.Text = FileGuru.OpenUTF8File(File);
                        ucCode.scintillaCode.Text = Memory.CODGENTAB;
                        ucBerta.scintillaBerta.Text = Memory.BERTATAB;
                        ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
                    }
                    else if (e.Node.ImageIndex == 1)
                    {
                        File += ".berta";
                        ReinicializarBerta();
                        ucBerta.scintillaBerta.Text = FileGuru.OpenUTF8File(File);
                        ucCode.scintillaCode.Text = Memory.CODGENTAB;
                        ucNino.scintillaNino.Text = Memory.NINOTAB;
                        ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
                    }
                    else if (e.Node.ImageIndex == 3)
                    {
                        File += ".dt";
                        ReinicializarTypes();
                        ucTypes.scintillaDataTypes.Text = FileGuru.OpenUTF8File(File);
                        ucCode.scintillaCode.Text = Memory.CODGENTAB;
                        ucBerta.scintillaBerta.Text = Memory.BERTATAB;
                        ucNino.scintillaNino.Text = Memory.NINOTAB;
                    }
                    else
                    {
                        ReinicializarCode();
                        ucCode.scintillaCode.Text = FileGuru.OpenUTF8File(File);
                        ucNino.scintillaNino.Text = Memory.NINOTAB;
                        ucBerta.scintillaBerta.Text = Memory.BERTATAB;
                        ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
                    }

                    Salida.txtSalida.Text += "\r\n[" + DateTime.Now.ToString() + "] " + Local.LOC004_OPENING_FILE + " " + File + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    Memory.NINOTAB = "";
                    Memory.CODGENTAB = "";
                    Memory.BERTATAB = "";
                    Memory.TYPESTAB = "";
                    System.GC.Collect();
                }
            }
            catch (Exception ex) {
                Salida.txtSalida.Text += "\r\n[" + DateTime.Now.ToString() + "] " + Local.LOC005_ERROR + " " + ex.Message + "...\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
            }
        }

        #endregion

        #region "Inicialización"

        private void RespaldarCodigos(){
            Memory.NINOTAB = ucNino.scintillaNino.Text;
            Memory.CODGENTAB = ucCode.scintillaCode.Text;
            Memory.BERTATAB = ucBerta.scintillaBerta.Text;
            Memory.TYPESTAB = ucTypes.scintillaDataTypes.Text;
        }

        private void ReinicializarNino() {
            DCNino.Dispose();
            DCCode.Dispose();
            DCBerta.Dispose();
            DCTypes.Dispose();
            MostrarDCCode();
            MostrarDCTypes();
            MostrarDCBerta();
            MostrarDCNino();
            DCNino.Activate();
        }

        private void ReinicializarBerta() {
            DCNino.Dispose();
            DCCode.Dispose();
            DCBerta.Dispose();
            DCTypes.Dispose();
            MostrarDCNino();
            MostrarDCCode();
            MostrarDCTypes();
            MostrarDCBerta();
            DCBerta.Activate();
        }

        private void ReinicializarTypes() {
            DCNino.Dispose();
            DCCode.Dispose();
            DCBerta.Dispose();
            DCTypes.Dispose();
            MostrarDCCode();
            MostrarDCBerta();
            MostrarDCNino();
            MostrarDCTypes();
            DCTypes.Activate();
        }

        private void ReinicializarCode() {
            DCNino.Dispose();
            DCCode.Dispose();
            DCBerta.Dispose();
            DCTypes.Dispose();
            MostrarDCBerta();
            MostrarDCNino();
            MostrarDCTypes();
            MostrarDCCode();
            DCCode.Activate();
        }

        private void MostrarDCNino()
        {
            DCNino = new DockContent();
            ucNino = new UCNino();
            ucNino.Dock = DockStyle.Fill;
            //scintillaNino.Padding = Control.p;
            DCNino.Dock = DockStyle.Fill;
            //Para poder navergarlo si el tamaño se encoje al moverlo de su lugar.
            DCNino.AutoScroll = true;
            //Lugar donde se agrega el panel en el DockPanel principal, .Document ocupa la mayor parte de espacio, centrado.
            DCNino.ShowHint = DockState.Document;
            //Título y el UserControl que va a contener
            DCNino.Text = global::Seisei.Properties.Strings.DCCodigo;
            DCNino.CloseButton = false;
            Bitmap iconoPNG = global::Seisei.Properties.Resources.documentattributen;
            IntPtr HIcon = iconoPNG.GetHicon();
            Icon icono = System.Drawing.Icon.FromHandle(HIcon);
            DCNino.Icon = icono;
            DCNino.Controls.Add(ucNino);
            DCNino.Show(dpPrincipal);
        }

        private void MostrarDCCode()
        {
            DCCode = new DockContent();
            ucCode = new UCCode();
            ucCode.Dock = DockStyle.Fill;
            //scintillaCode.Padding = Control.p;
            DCCode.Dock = DockStyle.Fill;
            //Para poder navergarlo si el tamaño se encoje al moverlo de su lugar.
            DCCode.AutoScroll = true;
            //Lugar donde se agrega el panel en el DockPanel principal, .Document ocupa la mayor parte de espacio, centrado.
            DCCode.ShowHint = DockState.Document;
            //Título y el UserControl que va a contener
            DCCode.Text = global::Seisei.Properties.Strings.DCGenerado;
            DCCode.CloseButton = false;
            Bitmap iconoPNG = global::Seisei.Properties.Resources.documentattributeg;
            IntPtr HIcon = iconoPNG.GetHicon();
            Icon icono = System.Drawing.Icon.FromHandle(HIcon);
            DCCode.Icon = icono;
            DCCode.Controls.Add(ucCode);
            DCCode.Show(dpPrincipal);
        }

        private void MostrarDCBerta()
        {
            DCBerta = new DockContent();
            ucBerta = new UCBerta();
            ucBerta.Dock = DockStyle.Fill;
            //scintillaBerta.Padding = Control.p;
            DCBerta.Dock = DockStyle.Fill;
            //Para poder navergarlo si el tamaño se encoje al moverlo de su lugar.
            DCBerta.AutoScroll = true;
            //Lugar donde se agrega el panel en el DockPanel principal, .Document ocupa la mayor parte de espacio, centrado.
            DCBerta.ShowHint = DockState.Document;
            //Título y el UserControl que va a contener
            DCBerta.Text = global::Seisei.Properties.Strings.DCBerta;
            DCBerta.CloseButton = false;
            Bitmap iconoPNG = global::Seisei.Properties.Resources.documentattributeb;
            IntPtr HIcon = iconoPNG.GetHicon();
            Icon icono = System.Drawing.Icon.FromHandle(HIcon);
            DCBerta.Icon = icono;
            DCBerta.Controls.Add(ucBerta);
            DCBerta.Show(dpPrincipal);
        }

        private void MostrarDCTypes()
        {
            DCTypes = new DockContent();
            ucTypes = new UCTypes();
            ucTypes.Dock = DockStyle.Fill;
            //scintillaTypes.Padding = Control.p;
            DCTypes.Dock = DockStyle.Fill;
            //Para poder navergarlo si el tamaño se encoje al moverlo de su lugar.
            DCTypes.AutoScroll = true;
            //Lugar donde se agrega el panel en el DockPanel principal, .Document ocupa la mayor parte de espacio, centrado.
            DCTypes.ShowHint = DockState.Document;
            //Título y el UserControl que va a contener
            DCTypes.Text = global::Seisei.Properties.Strings.DCTipos;
            DCTypes.CloseButton = false;
            Bitmap iconoPNG = global::Seisei.Properties.Resources.documentattributet;
            IntPtr HIcon = iconoPNG.GetHicon();
            Icon icono = System.Drawing.Icon.FromHandle(HIcon);
            DCTypes.Icon = icono;
            DCTypes.Controls.Add(ucTypes);
            DCTypes.Show(dpPrincipal);
        }

        private void MostrarDCHelp()
        {
            DCHelp = new DockContent();
            ucHelp = new UCAyuda();
            ucHelp.Dock = DockStyle.Fill;
            //scintillaHelp.Padding = Control.p;
            DCHelp.Dock = DockStyle.Fill;
            //Para poder navergarlo si el tamaño se encoje al moverlo de su lugar.
            DCHelp.AutoScroll = true;
            //Lugar donde se agrega el panel en el DockPanel principal, .Document ocupa la mayor parte de espacio, centrado.
            DCHelp.ShowHint = DockState.Document;
            //Título y el UserControl que va a contener
            DCHelp.Text = global::Seisei.Properties.Strings.DCContenidos;
            DCHelp.CloseButton = false;
            Bitmap iconoPNG = global::Seisei.Properties.Resources.questionframe;
            IntPtr HIcon = iconoPNG.GetHicon();
            Icon icono = System.Drawing.Icon.FromHandle(HIcon);
            DCHelp.Icon = icono;
            //ucHelp.wbAyuda.DocumentText = Global.Help.Contents;
            DCHelp.Controls.Add(ucHelp);
            DCHelp.Show(dpPrincipal);
        }

        private void MostrarDCOutput()
        {
            DCOutput = new DockContent();
            DCOutput.Dock = DockStyle.Fill;
            Salida = new UCSalida();
            Salida.Dock = DockStyle.Fill;
            //Para poder navergarlo si el tamaño se encoje al moverlo de su lugar.
            DCOutput.AutoScroll = true;
            //Lugar donde se agrega el panel en el DockPanel principal, .Document ocupa la mayor parte de espacio, centrado.
            DCOutput.ShowHint = DockState.DockBottom;
            //Título y el UserControl que va a contener
            DCOutput.Text = global::Seisei.Properties.Strings.DCSalida;
            DCOutput.CloseButton = false;
            Bitmap iconoPNG = global::Seisei.Properties.Resources.applicationterminal;
            IntPtr HIcon = iconoPNG.GetHicon();
            Icon icono = System.Drawing.Icon.FromHandle(HIcon);
            DCOutput.Icon = icono;
            DCOutput.Controls.Add(Salida);
            DCOutput.Show(dpPrincipal);
        }

        private void MostrarDCExplorer()
        {
            DCExplorer = new DockContent();
            DCExplorer.Dock = DockStyle.Fill;
            Explorador = new UCExplorador();
            Explorador.Dock = DockStyle.Fill;
            //Para poder navergarlo si el tamaño se encoje al moverlo de su lugar.
            DCExplorer.AutoScroll = true;
            //Lugar donde se agrega el panel en el DockPanel principal, .Document ocupa la mayor parte de espacio, centrado.
            DCExplorer.ShowHint = DockState.DockRight;
            //Título y el UserControl que va a contener
            DCExplorer.Text = global::Seisei.Properties.Strings.DCExplorador;
            DCExplorer.CloseButton = false;
            Bitmap iconoPNG = global::Seisei.Properties.Resources.nodeselectchild;
            IntPtr HIcon = iconoPNG.GetHicon();
            Icon icono = System.Drawing.Icon.FromHandle(HIcon);
            DCExplorer.Icon = icono;
            DCExplorer.Controls.Add(Explorador);
            DCExplorer.Show(dpPrincipal);
            Explorador.tvExplorador.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.tvExplorador_NodeMouseDoubleClick);
        }

        #endregion

        #region "Explorador"

        private void CargarExplorador()
        {
            Explorador.tvExplorador.Nodes[0].Nodes.Clear();
            CargarNodo(Explorador.tvExplorador.Nodes[0], Memory.WORKSPACE);
            Explorador.tvExplorador.Nodes[0].ExpandAll();
        }

        private void AgregarNodo(TreeNode nodo, string file, string Directory)
        {
            TreeNode nodo2;
            if (file.Substring(file.Length - 5).Equals(".nino"))
            {
                nodo2 = new TreeNode(file.Replace(Directory + "\\", "").Replace(".nino", ""), 2, 2);
            }
            else if (file.Substring(file.Length - 6).Equals(".berta"))
            {
                nodo2 = new TreeNode(file.Replace(Directory + "\\", "").Replace(".berta", ""), 1, 1);
            }
            else if (file.Substring(file.Length - 3).Equals(".dt"))
            {
                nodo2 = new TreeNode(file.Replace(Directory + "\\", "").Replace(".dt", ""), 3, 3);
            }
            else
            {
                nodo2 = new TreeNode(file.Replace(Directory + "\\", ""), 4, 4);
            }
            nodo.Nodes.Add(nodo2);
        }

        private void CargarNodo(TreeNode Nodo, string Path)
        {
            string[] Files = FileGuru.GetDirectoryFileList(Path);
            List<string> dirs = new List<string>();
            List<string> archs = new List<string>();
            foreach (string file in Files)
            {

                if (FileGuru.IsDirectory(file))
                {
                    dirs.Add(file);
                }
                else
                {
                    archs.Add(file);
                }
            }
            foreach (string d in dirs)
            {
                TreeNode nodo = new TreeNode(d.Replace(Path + "\\", ""), 0, 0);
                Nodo.Nodes.Add(nodo);
                CargarNodo(nodo, d);
            }
            foreach (string a in archs)
            {
                AgregarNodo(Nodo, a, Path);
            }
        }

        public void CargarCodigoNino()
        {
            DCOutput.Activate();
            Salida.txtSalida.Focus();
            Salida.txtSalida.Text += "\r\n[" + global::Seisei.Properties.Strings.NinoGenTitle +"]\r\n";
            Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
            Salida.txtSalida.ScrollToCaret();

            string SGBD = "";
            switch (Memory.INPUT_DBMS)
            {
                case (int)DBMS.MSSQL:
                    SGBD = "Microsoft SQL Server";
                    break;
            }
            Salida.txtSalida.Text += global::Seisei.Properties.Strings.NinoGenDBMS + ":   " + SGBD + "\r\n";
            Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
            Salida.txtSalida.ScrollToCaret();
            Salida.txtSalida.Text += global::Seisei.Properties.Strings.NinoGenDBName + ":   " + Memory.Database + "\r\n";
            Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
            Salida.txtSalida.ScrollToCaret();
            Salida.txtSalida.Text += global::Seisei.Properties.Strings.NinoGenTableQty + ":   " + Memory.DB_TABLES.Length + "\r\n";
            Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
            Salida.txtSalida.ScrollToCaret();
            Salida.txtSalida.Text += "\r\n";
            Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
            Salida.txtSalida.ScrollToCaret();
            if (Memory.GENERATING_NINO)
            {
                Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.NinoGenGenHeader + "...\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
                string NinoCode = MSSQL.GetNinoHeaderCode();
                NinoCode += "\n";
                if (Memory.ALL_TABLES)
                {
                    if (Memory.INPUT_DBMS == (int)DBMS.MSSQL)
                    {
                        for (int i = 0; i < Memory.DB_TABLES.Length; i++)
                        {
                            if (!Memory.DB_TABLES[i].Equals("sysdiagrams"))
                            {
                                Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.NinoGenGenTableCode + " " + Memory.DB_TABLES[i] + "...\r\n";
                                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                                Salida.txtSalida.ScrollToCaret();
                                NinoCode += MSSQL.GetTableNINOCode(Memory.DB_TABLES[i]);
                                NinoCode += "\n";
                            }
                        }
                    }
                }
                else
                {
                    if (Memory.INPUT_DBMS == (int)DBMS.MSSQL)
                    {
                        NinoCode += MSSQL.GetTableNINOCode(Memory.DB_TABLE_SINGLE);
                        Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.NinoGenGenTableCode + " " + Memory.DB_TABLE_SINGLE + "...\r\n";
                        Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                        Salida.txtSalida.ScrollToCaret();
                        NinoCode += "\n";
                    }
                }
                Memory.NINOTAB = NinoCode;
                Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.NinoGenDone + ".\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
                Salida.txtSalida.Focus();
            }
        }

        #endregion

        #region "I/O"

        private void AbrirArchivo()
        {
            Memory.NINOTAB = ucNino.scintillaNino.Text;
            Memory.CODGENTAB = ucCode.scintillaCode.Text;
            Memory.BERTATAB = ucBerta.scintillaBerta.Text;
            Memory.TYPESTAB = ucTypes.scintillaDataTypes.Text;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = global::Seisei.Properties.Strings.DCCodigo + " (*.nino)|*.nino|" + global::Seisei.Properties.Strings.DCBerta + " (*.berta)|*.berta|" + global::Seisei.Properties.Strings.DCTipos + " (*.dt)|*.dt";
            of.InitialDirectory = Memory.WORKSPACE;
            of.RestoreDirectory = true;
            if (of.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Salida.txtSalida.Text += "\r\n[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.LOCAbriendoArch + " " + of.FileName + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    if (of.FileName.Substring(of.FileName.Length - 5).Equals(".nino"))
                    {
                        ReinicializarNino();
                        ucNino.scintillaNino.Text = FileGuru.OpenUTF8File(of.FileName);
                        ucCode.scintillaCode.Text = Memory.CODGENTAB;
                        ucBerta.scintillaBerta.Text = Memory.BERTATAB;
                        ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
                    }
                    else if (of.FileName.Substring(of.FileName.Length - 6).Equals(".berta"))
                    {
                        ReinicializarBerta();
                        ucBerta.scintillaBerta.Text = FileGuru.OpenUTF8File(of.FileName);
                        ucNino.scintillaNino.Text = Memory.NINOTAB;
                        ucCode.scintillaCode.Text = Memory.CODGENTAB;
                        ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
                    }
                    else if (of.FileName.Substring(of.FileName.Length - 3).Equals(".dt"))
                    {
                        ReinicializarTypes();
                        ucTypes.scintillaDataTypes.Text = FileGuru.OpenUTF8File(of.FileName);
                        ucNino.scintillaNino.Text = Memory.NINOTAB;
                        ucCode.scintillaCode.Text = Memory.CODGENTAB;
                        ucBerta.scintillaBerta.Text = Memory.BERTATAB;
                        Memory.TYPESTAB = "";
                    }
                    else
                    {
                        ReinicializarCode();
                        ucCode.scintillaCode.Text = FileGuru.OpenUTF8File(of.FileName);
                        ucNino.scintillaNino.Text = Memory.NINOTAB;
                        ucBerta.scintillaBerta.Text = Memory.BERTATAB;
                        ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
                    }

                    Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.LOCOutputReady + ".\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    Explorador.tvExplorador.Nodes[0].Nodes.Clear();

                    Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOUpdatingExplorer + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    CargarExplorador();

                    Memory.NINOTAB = "";
                    Memory.CODGENTAB = "";
                    Memory.BERTATAB = "";
                    Memory.TYPESTAB = "";
                    System.GC.Collect();
                }
                catch (Exception ex)
                {
                    Salida.txtSalida.Text = global::Seisei.Properties.Strings.IOErrorOpeningFile + ": " + ex.Message;
                }
            }
        }

        private void GuardarArchivoNino()
        {

            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = global::Seisei.Properties.Strings.DCCodigo +  " (*.nino)|*.nino";
            sf.InitialDirectory = Memory.WORKSPACE;
            sf.RestoreDirectory = true;
            if (sf.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Salida.txtSalida.Text += "\r\n[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOSavingFile + " " + sf.FileName.Replace(".nino", "") + ".nino" + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    FileGuru.SaveUTF8File(sf.FileName.Replace(".nino", "") + ".nino", ucNino.scintillaNino.Text);

                    Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOFileSaved + ".\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    Explorador.tvExplorador.Nodes[0].Nodes.Clear();

                    Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOUpdatingExplorer + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    CargarExplorador();
                }
                catch (Exception ex)
                {
                    Salida.txtSalida.Text = global::Seisei.Properties.Strings.IOErrorSavingFile + ": " + ex.Message;
                }
            }
        }

        private void GuardarArchivoBerta()
        {
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = global::Seisei.Properties.Strings.DCBerta + " (*.berta)|*.berta";
            sf.InitialDirectory = Memory.WORKSPACE;
            sf.RestoreDirectory = true;
            if (sf.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Salida.txtSalida.Text += "\r\n[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOSavingFile + " " + sf.FileName.Replace(".berta", "") + ".berta" + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    FileGuru.SaveUTF8File(sf.FileName.Replace(".berta", "") + ".berta", ucBerta.scintillaBerta.Text);

                    Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOFileSaved + ".\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    Explorador.tvExplorador.Nodes[0].Nodes.Clear();

                    Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOUpdatingExplorer + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    CargarExplorador();
                }
                catch (Exception ex)
                {
                    Salida.txtSalida.Text = global::Seisei.Properties.Strings.IOErrorSavingFile + ": " + ex.Message;
                }
            }
        }

        private void GuardarArchivoDataTypes()
        {
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = global::Seisei.Properties.Strings.DCTipos + " (*.dt)|*.dt";
            sf.InitialDirectory = Memory.WORKSPACE;
            sf.RestoreDirectory = true;
            if (sf.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Salida.txtSalida.Text += "\r\n[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOSavingFile + " " + sf.FileName.Replace(".dt", "") + ".dt" + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    FileGuru.SaveUTF8File(sf.FileName.Replace(".dt", "") + ".dt", ucTypes.scintillaDataTypes.Text);

                    Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOFileSaved + ".\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    Explorador.tvExplorador.Nodes[0].Nodes.Clear();

                    Salida.txtSalida.Text += "[" + DateTime.Now.ToString() + "] " + global::Seisei.Properties.Strings.IOUpdatingExplorer + "...\r\n";
                    Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                    Salida.txtSalida.ScrollToCaret();

                    CargarExplorador();
                }
                catch (Exception ex)
                {
                    Salida.txtSalida.Text = global::Seisei.Properties.Strings.IOErrorSavingFile + ": " + ex.Message;
                }
            }
        }

        #endregion

        private void abrirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbOpen.PerformClick();
        }

        private void nuevoNinoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbNino.PerformClick();
        }

        private void nuevaPlantillaBertaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbBerta.PerformClick();
        }

        private void nuevoTiposDeDatosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbTypes.PerformClick();
        }

        private void tsbDatabase_Click(object sender, EventArgs e)
        {
            NINOAssistant ninoassis = new NINOAssistant();
            ninoassis.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ninoassis_FormClosed);
            ninoassis.ShowDialog();
        }

        private void tsbRunNino_Click(object sender, EventArgs e)
        {
            Salida.txtSalida.Text += "\r\n[" + global::Seisei.Properties.Strings.NinoInTitle  + "]\r\n";
            Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
            Salida.txtSalida.ScrollToCaret();
            bool correct = Database.ReadNino(ucNino.scintillaNino.Text);
            if (correct)
            {
                Salida.txtSalida.Text += "[" + DateTime.Now + "] " + global::Seisei.Properties.Strings.NinoInDone + ".\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
            }
            else
            {
                Salida.txtSalida.Text += "[" + DateTime.Now + "] " + global::Seisei.Properties.Strings.NinoInError + ": " + Memory.ERROR + ".\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
            }
        }

        private void tsbOpen_Click(object sender, EventArgs e)
        {
            AbrirArchivo();
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            if (DCNino.IsActivated)
            {
                GuardarArchivoNino();
            }
            else if (DCBerta.IsActivated)
            {
                GuardarArchivoBerta();
            }
            else if (DCTypes.IsActivated)
            {
                GuardarArchivoDataTypes();
            }
        }

        private void tsbNino_Click(object sender, EventArgs e)
        {
            RespaldarCodigos();
            ReinicializarNino();
            ucCode.scintillaCode.Text = Memory.CODGENTAB;
            ucBerta.scintillaBerta.Text = Memory.BERTATAB;
            ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
        }

        private void tsbBerta_Click(object sender, EventArgs e)
        {
            RespaldarCodigos();
            ReinicializarBerta();
            ucCode.scintillaCode.Text = Memory.CODGENTAB;
            ucNino.scintillaNino.Text = Memory.NINOTAB;
            ucTypes.scintillaDataTypes.Text = Memory.TYPESTAB;
        }

        private void tsbTypes_Click(object sender, EventArgs e)
        {
            RespaldarCodigos();
            ReinicializarTypes();
            ucCode.scintillaCode.Text = Memory.CODGENTAB;
            ucBerta.scintillaBerta.Text = Memory.BERTATAB;
            ucNino.scintillaNino.Text = Memory.NINOTAB;
        }

        private void tsbGenCode_Click(object sender, EventArgs e)
        {
            try
            {
                Salida.txtSalida.Text += "\r\n[" + global::Seisei.Properties.Strings.BertaInTitle + "]\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
                Salida.txtSalida.Text += "[" + DateTime.Now + "]" + global::Seisei.Properties.Strings.BertaInGen + "...\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
                ucCode.scintillaCode.Text = CodeGenerator.Generate(ucBerta.scintillaBerta.Text);
                ucCode.scintillaCode.ConfigurationManager.Language = DataTypes.GetDataType(1, "SCINTILLA");
                Salida.txtSalida.Text += "[" + DateTime.Now + "]" + global::Seisei.Properties.Strings.BertaInDone + ".\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
            }
            catch (Exception ex) {
                Salida.txtSalida.Text += "[" + DateTime.Now + "]" + global::Seisei.Properties.Strings.NinoInError + ": " + ex.Message + "\r\n";
                Salida.txtSalida.SelectionStart = Salida.txtSalida.Text.Length;
                Salida.txtSalida.ScrollToCaret();
            }
        }

        private void generarCódigoDesdePlantillaBertaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbGenCode.PerformClick();
        }

        private void contenidosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbContenidos.PerformClick();
        }

        private void tsbInicio_Click(object sender, EventArgs e)
        {
            Memory.START_SELECTION = (int)Memory.STARTOPT.Nothing;
            Welcome inicio = new Welcome();
            inicio.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.inicio_FormClosed);
            inicio.ShowDialog();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbAcerca.PerformClick();
        }

        private void tsbAcerca_Click(object sender, EventArgs e)
        {
            About acerca = new About();
            acerca.ShowDialog();
        }

        private void tsbContenidos_Click(object sender, EventArgs e)
        {
            DCHelp.Activate();
        }

        private void españolesESToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cargarLocalizacion("es-CR");
        }

        private void englishenUSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cargarLocalizacion("en-US");
        }

        private void salirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

    }
}
